package com.fau.wm.action.index;

import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.context.annotation.Scope;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;

import com.fau.wm.action.PublicAction;
import com.fau.wm.entity.MedicalAdmin;
import com.fau.wm.entity.MedicalStorage;
import com.fau.wm.entity.MedicalStorageDetail;
import com.fau.wm.util.FileNameEncoderUtil;
import com.fau.wm.util.SystemConfig;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ModelDriven;

/**
 * @desc 入库管理Action
 * @author kangyj
 * @datetime 2014年7月31日,下午4:43:44
 */
@Controller
@Scope("prototype")
@ParentPackage("default")
@Namespace("/")
public class StorageAction extends PublicAction implements ModelDriven<MedicalStorage> {

	private static final long serialVersionUID = 6866929232821739538L;
	
	private MedicalStorage storage = new MedicalStorage();
	
	/**
	 * @desc 初始化入库管理页面
	 * @return
	 * @author kangyj
	 * @datetime 2014年7月31日,下午4:44:17
	 */
	@Action(value = "storage_init", results = {@Result(name = SUCCESS, location = "storage_init.jsp")})
	public String init() {
		return SUCCESS;
	}
	
	/**
	 * @desc 查询仓库集合
	 * @return
	 * @author kangyj
	 * @datetime 2014年8月1日,下午8:09:13
	 */
	@Action(value = "storage_find_warehouse")
	public String findWarehouseList() {
		HttpServletResponse response = ServletActionContext.getResponse();
		MedicalAdmin admin = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		list = this.baseAllService.getBaseDataService().findWarehouseByHospital(admin.getEnterpriseId());
		formatJSON(response, list);
		return null;
	}
	
	/**
	 * @desc 查询入库单
	 * @return
	 * @author kangyj
	 * @datetime 2014年7月31日,下午4:47:26
	 */
	@Action(value = "storage_view")
	public String view() {
		HttpServletResponse response = ServletActionContext.getResponse();
		map = ActionContext.getContext().getParameters();
		MedicalAdmin admin = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		storage.setHospitalId(admin.getEnterpriseId());
		pageBean = this.baseAllService.getStorageManagerService().findStorageByPage(storage, map);
		map.clear();
		map.put("total", pageBean.getTotalRow());
		map.put("data", pageBean.getResult());
		formatJSON(response, map);
		return null;
	}
	
	/**
	 * @desc 添加入库单
	 * @return
	 * @author kangyj
	 * @datetime 2014年7月31日,下午4:45:20
	 */
	@Action(value = "storage_add", results = {@Result(name = SUCCESS, location = "storage_add.jsp")})
	public String add() {
		return SUCCESS;
	}
	
	/**
	 * @desc 编辑入库单
	 * @return
	 * @author kangyj
	 * @datetime 2014年7月31日,下午4:46:34
	 */
	@Action(value = "storage_edit", results = {@Result(name = SUCCESS, location = "storage_edit.jsp")})
	public String edit() {
		return SUCCESS;
	}
	
	/**
	 * @desc 保存入库单
	 * @return
	 * @author kangyj
	 * @datetime 2014年7月31日,下午8:31:56
	 */
	@Action(value = "storage_save")
	public String save() {
		HttpServletResponse response = ServletActionContext.getResponse();
		map = new HashMap<String, Object>();
		MedicalAdmin writeUser = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		Boolean flag = this.baseAllService.getStorageManagerService().saveStorage(storage, writeUser);
		if(flag){
			map.put("success", true);
		}else{
			map.put("success", false);
		}
		formatJSON(response, map);
		return null;
	}
	
	/**
	 * @desc 验证输入编码是否已存在
	 * @return
	 * @author suny
	 * @datetime 2014年9月4日,下午2:43:29
	 */
	@Action(value="storage_ver_serialnum")
	public String verSerialNum(){
		HttpServletResponse response = ServletActionContext.getResponse();
		map = new HashMap<String, Object>();
		MedicalAdmin admin = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		if(StringUtils.isNotBlank(storage.getSerialNum())){
			Boolean flag = this.baseAllService.getStorageManagerService().verSerialNum(storage.getSerialNum(), admin.getEnterpriseId());
			if(flag){
				map.put("result", true);
			}else{
				map.put("result", false);
			}
		}else{
			map.put("message", "error");
			}
		formatJSON(response, map);
		return null;
	}
	
	/**
	 * @desc 保存编辑入库基本信息
	 * @return
	 * @author kangyj
	 * @datetime 2014年8月2日,上午10:41:02
	 */
	@Action(value = "storage_save_edit")
	public String saveEdit(){
		HttpServletResponse response = ServletActionContext.getResponse();
		map = new HashMap<String, Object>();
		if(StringUtils.isNotBlank(storage.getId())){
			this.baseAllService.getStorageManagerService().saveEditStorage(storage);
			map.put("success", true);
		}else{
			map.put("message", "error");
			}
		formatJSON(response, map);
		return null;
	}
	
	/**
	 * @desc 批准入库
	 * @return
	 * @author kangyj
	 * @datetime 2014年8月9日,下午4:03:51
	 */
	@Action(value = "storage_storage")
	public String storage(){
		HttpServletResponse response = ServletActionContext.getResponse();
		map = new HashMap<String, Object>();
		MedicalAdmin auditUser = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		if(StringUtils.isNotBlank(storage.getId())){
			List<MedicalStorageDetail> storageDetailList = this.baseAllService.getStorageManagerService().findStorageDetailList(storage.getId());
			this.baseAllService.getInStockManagerService().saveInStock(storageDetailList);
			this.baseAllService.getStorageManagerService().updateStorageStatus(SystemConfig.STORAGE_STATUS_APPROVAL, storage.getId());
			this.baseAllService.getStorageManagerService().updateAuditUser(auditUser, storage.getId());
			map.put("success", true);
		}else{
			map.put("message", "error");
		}
		formatJSON(response, map);
		return null;
	}
	
	/**
	 * @desc 查看入库单详细
	 * @return
	 * @author kangyj
	 * @datetime 2014年8月11日,下午3:23:06
	 */
	@Action(value = "storage_data_view", results = {@Result(name = SUCCESS, location = "storage_data_view.jsp")})
	public String dataView(){
		return SUCCESS;
	}
	
	/**
	 * @desc 删除入库表
	 * @return
	 * @author kangyj
	 * @datetime 2014年8月11日,下午4:38:19
	 */
	@Action(value = "storage_del")
	public String del(){
		HttpServletResponse response = ServletActionContext.getResponse();
		map = new HashMap<String, Object>();
		if(StringUtils.isNotBlank(storage.getId())){
			this.baseAllService.getStorageManagerService().delStorage(storage);
			map.put("success", true);
			formatJSON(response, map);
		}
		return null;
	}
	
	/**
	 * @desc 入库审核页面初始化
	 * @return
	 * @author kangyj
	 * @datetime 2014年8月18日,下午10:05:57
	 */
	@Action(value = "storage_audit_init", results = {@Result(name = SUCCESS, location = "storage_audit_init.jsp")})
	public String auditInit(){
		return SUCCESS;
	}
	
	/**
	 * @desc 查询待审核入库单
	 * @return
	 * @author kangyj
	 * @datetime 2014年8月18日,下午10:03:31
	 */
	@Action(value = "storage_audit_view")
	public String auditView(){
		HttpServletResponse response = ServletActionContext.getResponse();
		map = ActionContext.getContext().getParameters();
		MedicalAdmin admin = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		storage.setHospitalId(admin.getEnterpriseId());
		pageBean = this.baseAllService.getStorageManagerService().findStorageAuditByPage(map, storage);
		map.clear();
		map.put("total", pageBean.getTotalRow());
		map.put("data", pageBean.getResult());
		formatJSON(response, map);
		return null;
	}
	
	/**
	 * @desc 入库审核
	 * @return
	 * @author kangyj
	 * @datetime 2014年8月18日,下午11:57:09
	 */
	@Action(value = "storage_audit", results = {@Result(name = SUCCESS, location = "storage_audit.jsp")})
	public String audit() {
		return SUCCESS;
	}
	
	/**
	 * @desc 不同意入库，更新入库状态
	 * @return
	 * @author kangyj
	 * @datetime 2014年8月19日,上午12:36:43
	 */
	@Action(value = "storage_audit_reject")
	public String reject(){
		HttpServletResponse response = ServletActionContext.getResponse();
		map = new HashMap<String, Object>();
		if(StringUtils.isNotBlank(storage.getId())){
			MedicalAdmin auditUser = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			this.baseAllService.getStorageManagerService().updateStorageStatus(SystemConfig.STORAGE_STATUS_REJECT, storage.getId());
			this.baseAllService.getStorageManagerService().updateAuditUser(auditUser, storage.getId());
			map.put("success", true);
		}else{
			map.put("message", "error");
			}
		formatJSON(response, map);
		return null;
	}
	
	/**
	 * @desc 入库单导出
	 * @return
	 * @author kangyj
	 * @datetime 2014年11月27日,下午6:18:35
	 */
	@Action(value="storage_export")
	public String export(){
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpServletRequest request = ServletActionContext.getRequest();
		try {
			response.addHeader("Content-Disposition", "attachment;filename=" + FileNameEncoderUtil.encode(request,"药品入库表.xls"));
			response.setContentType("application/vnd.ms-excel");
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			Workbook workbook = this.baseAllService.getStorageManagerService().exportStorageData(storage.getId());
			workbook.write(toClient);
			toClient.flush();
			toClient.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * @desc 提交入库单审核
	 * @return null
	 * @author liy
	 * @datetime 2014年12月24日,上午9:11:59
	 */
	@Action(value = "storage_to_audit")
	public String toAudit(){
		HttpServletResponse response = ServletActionContext.getResponse();
		map = new HashMap<String, Object>();
		boolean flag = this.baseAllService.getStorageManagerService().toAudit(this.storage.getId());
		if(flag){
			map.put("success", true);
		}else{
			map.put("success", false);
		}
		formatJSON(response, map);
		return null;
	}
	
	/**
	 * @desc 下载药品入库导入模版
	 * @return null
	 * @author liy
	 * @datetime 2014年12月26日,上午11:31:52
	 */
	@Action(value = "storage_download")
	public String medicineDownload() {
		this.download(SystemConfig.MEDICINE_STORAGE_MASTERPLATE, "入库单导入模版.xls");
		return null;
	}
	
	public MedicalStorage getStorage() {
		return storage;
	}
	
	public void setStorage(MedicalStorage storage) {
		this.storage = storage;
	}

	@Override
	public MedicalStorage getModel() {
		return storage;
	}

}
